package com.android.fragmentdemo.roomdb
import android.content.Context
import android.util.Log
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

object RoomDBEntrance {
    /*
       Kotlin/Java 类型	           SQLite 类型
       Int, Long, Short, Byte	   INTEGER
       Double, Float	           REAL
       String	                   TEXT
       ByteArray	               BLOB
       Boolean	                   INTEGER (0 或 1)
    * */
    private const val TAG = "RoomDBEntrance"
    private const val DB_NAME = "RoomDB.db"

    private lateinit var dataBase: AppRoomDataBase

    fun init(context: Context) {
        Log.d(TAG, "RoomDBEntrance--init")
        dataBase = Room.databaseBuilder(
            context,
            AppRoomDataBase::class.java,
            DB_NAME
        ).addMigrations(
            RoomMigration1To2(1, 2),
            RoomMigration2To3(2, 3),
            RoomMigration3To4(3, 4)
        )
            //.fallbackToDestructiveMigration()
            .allowMainThreadQueries() //允许在主线程上查询
            .addCallback(RoomCallback())
            .build()
    }

    fun getRoomDataBase() : AppRoomDataBase {
        return dataBase
    }

    private class RoomCallback : RoomDatabase.Callback() {
        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)
            Log.d(TAG, "RoomCallback--onCreate")
        }

        override fun onOpen(db: SupportSQLiteDatabase) {
            super.onOpen(db)
            Log.d(TAG, "RoomCallback--onOpen")
        }
    }

    private class RoomMigration1To2(startVersion: Int, endVersion: Int) :
        Migration(startVersion, endVersion) {
        //alter table 表名 drop constraint 约束名字
        //alter table 表名 add constraint 约束名字 DEFAULT 默认值 for 字段名称
        override fun migrate(database: SupportSQLiteDatabase) {
            Log.d(TAG, "RoomMigration1To2--migrate")
            try {
                //database.beginTransaction()
                //database.execSQL("ALTER TABLE user ADD COLUMN DEFAULT ${""} for job ")
                database.execSQL("ALTER TABLE user ADD COLUMN money INTEGER NOT NULL DEFAULT 0")
            } catch (ex: Exception) {
                Log.d(TAG, "error-message:${ex.message}")
            }
            //finally {
            //    database.endTransaction()
            //}
        }
    }

    private class RoomMigration2To3(startVersion: Int, endVersion: Int) :
        Migration(startVersion, endVersion) {
        //alter table 表名 drop constraint 约束名字
        //alter table 表名 add constraint 约束名字 DEFAULT 默认值 for 字段名称
        override fun migrate(database: SupportSQLiteDatabase) {
            Log.d(TAG, "RoomMigration2To3--migrate")
            try {
                database.execSQL("ALTER TABLE user ADD COLUMN job TEXT NOT NULL DEFAULT ''")
            } catch (ex: Exception) {
                Log.d(TAG, "RoomMigration2To3--error-message:${ex.message}")
            }
        }
    }

    private class RoomMigration3To4(startVersion: Int, endVersion: Int) :
        Migration(startVersion, endVersion) {
        //alter table 表名 drop constraint 约束名字
        //alter table 表名 add constraint 约束名字 DEFAULT 默认值 for 字段名称
        override fun migrate(database: SupportSQLiteDatabase) {
            Log.d(TAG, "RoomMigration3To4--migrate")
            database.beginTransaction()
            try {
                /*
                * database.execSQL("""
                    CREATE TABLE user_temp (
                        id INTEGER PRIMARY KEY NOT NULL,
                        name TEXT NOT NULL,
                        email TEXT NOT NULL,
                        phone TEXT DEFAULT '',
                        age INTEGER DEFAULT 0
                    )
                """.trimIndent())
                * */
                database.execSQL(""" 
                    CREATE TABLE pet(
                     idCard TEXT PRIMARY KEY NOT NULL DEFAULT '',
                     name TEXT NOT NULL DEFAULT '',
                     foods TEXT NOT NULL DEFAULT ''
                    )
                """.trimIndent())
                database.execSQL("ALTER TABLE user ADD COLUMN petList TEXT NOT NULL DEFAULT ''")
                Log.d(TAG, "database.execSQL--database.execSQL")
                database.setTransactionSuccessful()
            } catch (ex: Exception) {
                Log.d(TAG, "RoomMigration3To4--error-message:${ex.message}")
            } finally {
                database.endTransaction()
            }
        }
    }

}